import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide Response;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:s_utils/src/size.dart';
import 'package:url_launcher/url_launcher.dart';

import 'logger.dart';
import 'widgets/dialog_widget.dart';

class AppVersion {
  static Future<bool> hasNewVersion(String newVersion, String newBuildNumber, {String platform = "PROD"}) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appVersion = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

    // String newV = "2.0.8".replaceAll(".", "");
    String newV = newVersion.replaceAll(".", "");
    String appV = appVersion.replaceAll(".", "");

    bool hasN = int.parse(newV) > int.parse(appV);
    if (int.parse(newBuildNumber) > int.parse(buildNumber)) hasN = true;

    logger.w("$platform Has New Version: $hasN, App: $appVersion+$buildNumber => Api: $newVersion+$newBuildNumber");
    return hasN;
  }

  static checkPgyVersion({required Map<String, dynamic> data, required String testflightUrl}) async {
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String appVersion = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;

      Dio dio = Dio(BaseOptions(headers: {"Content-Type": "application/x-www-form-urlencoded"}));
      String url = "https://tools.mhter.com/api/app_version";
      Response res = await dio.postUri(Uri.parse(url), data: data);
      Map<String, dynamic> resData = res.data['data'] ?? {};
      bool hasUpdate = false;
      hasUpdate = await hasNewVersion(
        resData['buildVersion'] ?? '0',
        resData['buildVersionNo'] ?? '0',
        platform: "PGY",
      );

      if (hasUpdate) {
        Get.dialog(
          PopScope(
            canPop: false,
            child: SDialogWidget(
              iconStatus: "warning",
              title: "new_version_title".tr,
              message:
              "${"new_version_desc".tr} \n\n${appVersion}+${buildNumber}"
                  "\n↓↓↓↓↓↓\n${resData['buildVersion']}+${resData['buildVersionNo']}",
              showFirstBtn: true,
              showSecondBtn: true,
              height: 800.r,
              actionTexts: const ["Close", "Update"],
              secondAction: () {
                launchUrl(
                  Uri.parse(GetPlatform.isIOS ? testflightUrl : resData['appURl']),
                  mode: LaunchMode.externalApplication,
                );
              },
            ),
          ),
          barrierDismissible: data['is_forced'] != true,
          useSafeArea: false,
          barrierColor: Colors.transparent,
          transitionCurve: Curves.easeInCubic,
        );
      }
    } catch (e) {
      logger.e(e);
    }
  }

  static checkMhterVersion({required Map<String, dynamic> data, required String testflightUrl}) async {
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String appVersion = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;

      Dio dio = Dio(
        BaseOptions(headers: {
          "Accept": "application/json", "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json; charset=utf-8",
        }),
      );
      data['page'] = 1;
      data['per_page'] = 1;

      String url = "https://apps.mhter.com/api/apps/versions";
      Response res = await dio.request(url, queryParameters: data);
      List releases = res.data['releases'];
      Map<String, dynamic> latest = releases.first ?? {};

      bool hasUpdate = false;
      hasUpdate = await hasNewVersion(
        latest['release_version'] ?? '0',
        latest['build_version'] ?? '0',
        platform: "棉花糖",
      );

      if (hasUpdate) {
        Get.dialog(
          PopScope(
            canPop: false,
            child: SDialogWidget(
              iconStatus: "warning",
              title: "new_version_title".tr,
              message:
              "${"new_version_desc".tr} \n\n${appVersion}+${buildNumber}"
                  "\n↓↓↓↓↓↓\n${latest['release_version']}+${latest['build_version']}",
              showFirstBtn: true,
              showSecondBtn: true,
              height: 800.r,
              actionTexts: const ["Close", "Update"],
              secondAction: () {
                launchUrl(
                  Uri.parse(GetPlatform.isIOS ? testflightUrl : latest['install_url']),
                  mode: LaunchMode.externalApplication,
                );
              },
            ),
          ),
          barrierDismissible: data['is_forced'] != true,
          useSafeArea: false,
          barrierColor: Colors.transparent,
          transitionCurve: Curves.easeInCubic,
        );
      }
    } catch (e) {
      logger.e(e);
    }
  }
}
